// auth/index.js
/**
 * 认证页面数据接口
 * @typedef {Object} AuthPageData
 * @property {boolean} loading
 */

/**
 * 粒子接口
 * @typedef {Object} Particle
 * @property {number} x
 * @property {number} y
 * @property {number} vx
 * @property {number} vy
 * @property {number} size
 * @property {number} opacity
 * @property {number} life
 */

Page({
  data: {
    loading: false,
    loginMode: 'auto', // 'auto' | 'admin' | 'partner'
    showPasswordInput: false,
    password: '',
    userRole: '', // 'admin' | 'partner'
    isFirstTime: true
  },
  
  particles: [],
  animationId: 0,
  canvas: null,
  ctx: null,
  
  onLoad() {
    this.initParticleBackground();
    this.checkAutoLogin();
  },
  
  onUnload() {
    if (this.animationId) {
      this.canvas?.cancelAnimationFrame(this.animationId);
    }
  },
  
  // 初始化粒子背景
  initParticleBackground() {
    const query = wx.createSelectorQuery();
    query.select('#particle-canvas')
      .fields({ node: true, size: true })
      .exec(res => {
        if (!res[0]) return;
        
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const dpr = wx.getSystemInfoSync().pixelRatio;
        
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.scale(dpr, dpr);
        
        this.canvas = canvas;
        this.ctx = ctx;
        
        // 初始化粒子
        this.initParticles(res[0].width, res[0].height);
        
        // 开始动画
        this.animate();
      });
  },
  
  // 初始化粒子
  initParticles(width, height) {
    this.particles = [];
    const particleCount = 50;
    
    for (let i = 0; i < particleCount; i++) {
      this.particles.push({
        x: Math.random() * width,
        y: Math.random() * height,
        vx: (Math.random() - 0.5) * 0.5,
        vy: (Math.random() - 0.5) * 0.5,
        size: Math.random() * 3 + 1,
        opacity: Math.random() * 0.5 + 0.2,
        life: Math.random() * 100 + 50
      });
    }
  },
  
  // 动画循环
  animate() {
    if (!this.ctx || !this.canvas) return;
    
    const { width, height } = this.canvas;
    const ctx = this.ctx;
    
    // 清除画布
    ctx.clearRect(0, 0, width, height);
    
    // 更新和绘制粒子
    this.particles.forEach((particle, index) => {
      // 更新位置
      particle.x += particle.vx;
      particle.y += particle.vy;
      particle.life--;
      
      // 边界检测
      if (particle.x < 0 || particle.x > width) particle.vx *= -1;
      if (particle.y < 0 || particle.y > height) particle.vy *= -1;
      
      // 重生粒子
      if (particle.life <= 0) {
        particle.x = Math.random() * width;
        particle.y = Math.random() * height;
        particle.life = Math.random() * 100 + 50;
      }
      
      // 绘制粒子
      ctx.save();
      ctx.globalAlpha = particle.opacity;
      ctx.fillStyle = '#ffffff';
      ctx.beginPath();
      ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
      ctx.fill();
      ctx.restore();
    });
    
    // 绘制连线
    this.drawConnections();
    
    // 继续动画
    this.animationId = this.canvas.requestAnimationFrame(() => {
      this.animate();
    });
  },
  
  // 绘制粒子间的连线
  drawConnections() {
    const ctx = this.ctx;
    const maxDistance = 100;
    
    for (let i = 0; i < this.particles.length; i++) {
      for (let j = i + 1; j < this.particles.length; j++) {
        const p1 = this.particles[i];
        const p2 = this.particles[j];
        
        const distance = Math.sqrt(
          Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)
        );
        
        if (distance < maxDistance) {
          const opacity = (1 - distance / maxDistance) * 0.2;
          
          ctx.save();
          ctx.globalAlpha = opacity;
          ctx.strokeStyle = '#ffffff';
          ctx.lineWidth = 1;
          ctx.beginPath();
          ctx.moveTo(p1.x, p1.y);
          ctx.lineTo(p2.x, p2.y);
          ctx.stroke();
          ctx.restore();
        }
      }
    }
  },
  
  // 自动检测登录状态
  async checkAutoLogin() {
    try {
      const loginRes = await wx.login();
      
      // 调用后端检查绑定状态
      const res = await wx.request({
        url: getApp().globalData.apiBase + '/api/auth/check-binding',
        method: 'POST',
        data: {
          code: loginRes.code
        }
      });
      
      if (res.data.code === 0 && res.data.data.isBound) {
        // 已绑定用户，直接登录
        const userRole = res.data.data.role;
        this.setData({ userRole });
        
        if (userRole === 'partner') {
          // 她的无感登录
          this.autoLoginAsPartner(res.data.data);
        } else {
          // 您需要密码验证
          this.setData({ 
            loginMode: 'admin',
            showPasswordInput: true 
          });
        }
      } else {
        // 未绑定，显示初始设置
        this.setData({ 
          loginMode: 'setup',
          isFirstTime: true 
        });
      }
    } catch (error) {
      console.error('检查登录状态失败:', error);
      this.setData({ loginMode: 'setup' });
    }
  },
  
  // 她的无感登录
  async autoLoginAsPartner(userData) {
    const app = getApp();
    app.globalData.userInfo = userData.user;
    app.globalData.token = userData.token;
    app.globalData.userRole = 'partner';
    
    wx.setStorageSync('token', userData.token);
    wx.setStorageSync('userInfo', userData.user);
    wx.setStorageSync('userRole', 'partner');
    
    // 设置她的主题
    app.globalData.currentTheme = 'partner';
    
    wx.showToast({
      title: '欢迎回来 ♡',
      icon: 'none',
      duration: 1500
    });
    
    setTimeout(() => {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }, 1500);
  },
  
  // 密码输入处理
  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
  },
  
  // 管理员密码登录
  async onAdminLogin() {
    if (!this.data.password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    try {
      const loginRes = await wx.login();
      
      const res = await wx.request({
        url: getApp().globalData.apiBase + '/api/auth/admin-login',
        method: 'POST',
        data: {
          code: loginRes.code,
          password: this.data.password
        }
      });
      
      if (res.data.code === 0) {
        const app = getApp();
        app.globalData.userInfo = res.data.data.user;
        app.globalData.token = res.data.data.token;
        app.globalData.userRole = 'admin';
        
        wx.setStorageSync('token', res.data.data.token);
        wx.setStorageSync('userInfo', res.data.data.user);
        wx.setStorageSync('userRole', 'admin');
        
        // 设置您的主题
        app.globalData.currentTheme = 'admin';
        
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });
        
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
      } else {
        throw new Error(res.data.message || '密码错误');
      }
    } catch (error) {
      console.error('登录失败:', error);
      wx.showToast({
        title: error.message || '登录失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },
  
  // 初始设置 - 获取手机号
  async onGetPhoneNumber(e) {
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      wx.showToast({
        title: '需要授权才能继续',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    try {
      const loginRes = await wx.login();
      
      const res = await wx.request({
        url: getApp().globalData.apiBase + '/api/auth/setup',
        method: 'POST',
        data: {
          code: loginRes.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        }
      });
      
      if (res.data.code === 0) {
        // 跳转到角色选择页面
        wx.navigateTo({
          url: '/pages/auth/role-select'
        });
      } else {
        throw new Error(res.data.message || '设置失败');
      }
    } catch (error) {
      console.error('设置失败:', error);
      wx.showToast({
        title: error.message || '设置失败，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },
  
  // 显示隐私政策
  showPrivacy() {
    wx.showModal({
      title: '隐私政策',
      content: '我们承诺保护您的隐私安全，仅在必要时收集和使用您的个人信息，用于提供更好的服务体验。',
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 显示忘记密码
  showForgotPassword() {
    wx.showModal({
      title: '忘记密码',
      content: '请联系管理员重置密码，或使用微信重新设置',
      confirmText: '重新设置',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            loginMode: 'setup'
          });
        }
      }
    });
  }
});